All files / src/app/api/collections/[id]/pool/photos/[photoId]/file route.ts

93.33% Statements 14/15
100% Branches 9/9
100% Functions 1/1
92.85% Lines 13/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                5x           9x 9x 1x     8x   8x 8x       8x 8x   4x   4x 2x     2x                              
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { PhotoController } from "@/server/api/photos";
import { requireApiCapability } from "@/server/dal/collection-access";
import { servePhotoFile } from "@/lib/photo-serving";
 
// sharp (used by servePhotoFile) is a native addon — pin the Node runtime.
export const runtime = "nodejs";
 
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; photoId: string }> },
) {
  const session = await getSession();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
 
  const db = getDb();
 
  try {
    const { id, photoId } = await params;
    // Authz BEFORE existence (purses-ct0) — see the item /file route for the rationale:
    // resolving the photo first would let a non-member distinguish 404 from 403.
    // items:read = curator — any curator may view pool photo files (full-curator model).
    const access = await requireApiCapability(db, id, session.user.id, "items:read");
    if (access instanceof NextResponse) return access;
 
    const photo = await PhotoController.fromDb(db).findById(photoId);
    // Only this collection's pooled (unassigned) photos are served here.
    if (!photo || photo.collectionId !== id || photo.itemId !== null) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
 
    return servePhotoFile(
      {
        blobKey: photo.blobKey,
        mimeType: photo.mimeType,
        photoId: photo.id,
        collectionId: id,
        updatedAt: photo.updatedAt,
        rotation: photo.rotation,
      },
      request
    );
  } catch {
    return NextResponse.json({ error: "Photo fetch failed" }, { status: 500 });
  }
}